import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

class UserManager {
    private List<User> users = new ArrayList<>();
    private final String FILE_NAME = "users.txt";

    public UserManager() { loadUsers(); }

    // MD5加密
    public static String md5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : messageDigest) sb.append(String.format("%02x", b));
            return sb.toString();
        } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); }
    }

    private void loadUsers() {
        File file = new File(FILE_NAME);
        if (!file.exists()) {
            // 默认管理员
            String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            users.add(new User("U001", "admin", md5("ynuinfo#777"), "admin", "00000000000", now));
            saveUsers();
            return;
        }
        try (BufferedReader br = new BufferedReader(new FileReader(FILE_NAME))) {
            String line;
            while ((line = br.readLine()) != null) {
                User u = User.fromString(line);
                if (u != null) users.add(u);
            }
        } catch (IOException e) { e.printStackTrace(); }
    }

    public void saveUsers() {
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(FILE_NAME))) {
            for (User u : users) {
                bw.write(u.toString());
                bw.newLine();
            }
        } catch (IOException e) { e.printStackTrace(); }
    }

    public User login(String username, String password) {
        String pwdHash = md5(password);
        for (User u : users) {
            if (u.getUsername().equals(username) && u.getPasswordHash().equals(pwdHash)) {
                return u;
            }
        }
        return null;
    }

    public void register(String username, String password, String role, String phone) {
        String id = "U" + String.format("%03d", users.size() + 1);
        String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        User newUser = new User(id, username, md5(password), role, phone, now);
        users.add(newUser);
        saveUsers();
    }

    public void listUsers() {
        for (User u : users) {
            System.out.println(u.getUserId() + " | " + u.getUsername() + " | " + u.getRole() + " | " + u.getPhone() + " | " + u.getRegisterTime());
        }
    }
}